package com.ruoyi.consumer.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.consumer.domain.CCar;
import com.ruoyi.consumer.domain.CCompany;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.domain.CompanyBind;
import com.ruoyi.consumer.domain.car.CarInfoElement;
import com.ruoyi.consumer.domain.car.CarInfoJson;
import com.ruoyi.consumer.service.impl.CCarServiceImpl;
import com.ruoyi.consumer.service.impl.CCompanyServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import com.ruoyi.consumer.service.impl.CompanyBindServiceImpl;
import com.ruoyi.consumer.utils.redis.CompanyCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: lizhouwei
 * @ date : 2023/12/10
 * @description: 车队经理
 */
@Api(tags = "车队经理")
@RestController
@RequestMapping("/api/driverManager")
public class DriverManagerController {

    @Autowired
    private CUserServiceImpl cUserService;

    @Autowired
    private CompanyBindServiceImpl companyBindService;

    @Autowired
    private CCompanyServiceImpl companyService;

    @Autowired
    private CCarServiceImpl carService;

    @Autowired
    private CompanyCache companyCache;

    /**
     * 绑定车队长
     *
     * @param mangerId
     * @param driverLeaderId
     * @return
     */
    @ApiOperation("绑定车队长")
    @GetMapping("/toManager")
    public AjaxResult requirementList(@ApiParam(value = "经理id", required = true) Integer mangerId,
                                      @ApiParam(value = "车队长id", required = true) Integer driverLeaderId) {

        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 2, "该用户不是车队经理");
        //查询车队长
        CUser cUser1 = cUserService.selectCUserByUserId(driverLeaderId);
        Assert.notNull(cUser1, "车队长不存在");
        //绑定车队长
        //查询绑定
        CompanyBind companyBind1 = new CompanyBind();
        companyBind1.setSysUserId(Long.valueOf(driverLeaderId));
        List<CompanyBind> companyBinds1 = companyBindService.selectCompanyBindList(companyBind1);
        if (!companyBinds1.isEmpty()) {
            for (CompanyBind bind : companyBinds1) {
                if (Objects.equals(bind.getMangerId(), mangerId))
                    return AjaxResult.error("该用户已经是该经理的车队长");
            }
            return AjaxResult.error("该用户已经是其他经理的车队长");
        }
        //先删掉之前初始的绑定司机因为现在该用户是车队经理
        CompanyBind bind = new CompanyBind();
        bind.setConsumerId(mangerId);
        List<CompanyBind> companyBinds = companyBindService.selectCompanyBindList(bind);
        if (companyBinds.size() > 0) {
            companyBinds.forEach(companyBind -> {
                companyBindService.deleteCompanyBindByBindId(companyBind.getBindId());
            });
        }
        CompanyBind companyBind = new CompanyBind();
        companyBind.setCompanyId(cUser.getCompanyId());
        companyBind.setMangerId(mangerId);
        companyBind.setSysUserId(Long.valueOf(driverLeaderId));
        //更新用户信息
        //如果他是经理就不执行更新操作
        if (cUser1.getUserRole() != 2) {
            cUser1.setUserRole(1);
        }
        cUser1.setCompanyId(cUser.getCompanyId());
        cUserService.updateCUser(cUser1);
        return AjaxResult.success(companyBindService.insertCompanyBind(companyBind));
    }

    @ApiOperation("查询车队经理手下的车队长")
    @GetMapping("/selectManagerLeader")
    public AjaxResult selectManagerLeader(@ApiParam(value = "经理id", required = true) Integer mangerId) {
        // 查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 2, "该用户不是车队经理");

        // 查询车队长
        CompanyBind companyBind = new CompanyBind();
        companyBind.setMangerId(mangerId);
        List<CompanyBind> companyBinds = companyBindService.selectCompanyBindList(companyBind);

        Set<Integer> uniqueUserIds = new HashSet<>();  // 使用 Set 存储唯一的用户ID
        List<AjaxResult> cUsers = new ArrayList<>();

        for (CompanyBind bind : companyBinds) {
            CUser cUser1 = cUserService.selectCUserByUserId(Math.toIntExact(bind.getSysUserId()));
            if (cUser1 != null && uniqueUserIds.add(cUser1.getUserId())) {  // 检查并添加到集合
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("userId", cUser1.getUserId());
                ajaxResult.put("userPhone", cUser1.getUserPhone());
                ajaxResult.put("value", cUser1.getUserId());
                ajaxResult.put("label", cUser1.getUserName());
                cUsers.add(ajaxResult);
            }
        }

        return AjaxResult.success(cUsers);
    }


    /**
     * 查询车队长手下的司机及车辆信息
     *
     * @return
     */
    @ApiOperation("查询车队长手下的司机及车辆信息")
    @GetMapping("/selectManagerDriver")
    public AjaxResult selectManagerDriver(@ApiParam(value = "车队长", required = true) Integer carLeaderId) {
        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(carLeaderId);
        Assert.notNull(cUser, "车队长不存在");
        Assert.isTrue(cUser.getUserRole() == 1, "该用户不是车队长");
        //查询车队长
        CompanyBind companyBind = new CompanyBind();
        companyBind.setSysUserId(Long.valueOf(carLeaderId));
        List<CompanyBind> companyBinds = companyBindService.selectCompanyBindList(companyBind);
        List<AjaxResult> cUsers = new ArrayList<>();
        for (CompanyBind bind : companyBinds) {
            CUser cUser1 = cUserService.selectCUserByUserId(bind.getConsumerId());
            if (cUser1 != null) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("userId", cUser1.getUserId());
                ajaxResult.put("userName", cUser1.getUserName());
                ajaxResult.put("userPhone", cUser1.getUserPhone());
                //查询车辆信息
                if (cUser1.getCarId() != null && cUser1.getCarId() != 0) {
                    CCar cCar = carService.selectCCarByCarId(cUser1.getCarId());
                    if (cCar != null) {
                        ajaxResult.put("carId", cCar.getCarId());
                        ajaxResult.put("plateNum", cCar.getPlateNum());
                    }
                } else {
                    ajaxResult.put("carId", 0);
                    ajaxResult.put("plateNum", "无");
                }
                ajaxResult.put("userStatus", cUser1.getCarId() == 0 ? "空闲" : "有车");
                cUsers.add(ajaxResult);
            }

        }
        return AjaxResult.success(cUsers);
    }

    /**
     * 查询 公司下空闲的司机
     *
     * @return
     */
    @ApiOperation("查询公司空闲的司机(车队长)")
    @GetMapping("/selectManagerFreeDriver")
    public AjaxResult selectManagerFreeDriver(@ApiParam(value = "车队长", required = true) Integer carLeaderId) {
        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(carLeaderId);
        Assert.notNull(cUser, "车队长不存在");
        Assert.isTrue(cUser.getUserRole() == 1, "该用户不是车队长");
        //查询车队长
        CompanyBind companyBind = new CompanyBind();
        companyBind.setCompanyId(cUser.getCompanyId());
        List<CompanyBind> companyBinds = companyBindService.selectCompanyBindList(companyBind);
        List<CUser> cUsers = new ArrayList<>();
        for (CompanyBind bind : companyBinds) {
            CUser cUser1 = cUserService.selectCUserByUserId(bind.getConsumerId());
            if (cUser1 != null && cUser1.getCarId() == 0) {
                cUsers.add(cUser1);
            }
        }
        return AjaxResult.success(cUsers);
    }

    /**
     * 上传车辆信息
     *
     * @param carInfoJson
     * @return
     */
    @ApiOperation("上传车辆信息")
    @PostMapping("/upCarInfo")
    public AjaxResult upCarInfo(@RequestBody CarInfoJson carInfoJson) {
        Integer userId = carInfoJson.getUserid();
        CUser cUser = cUserService.selectCUserByUserId(userId);
        //用户不存在直接返回
        if (cUser == null || cUser.getCarId() == null) {
            return AjaxResult.error("用户不存在");
        }

        List<CarInfoElement> carInfoElementList = carInfoJson.getCarInfoElements();
        System.out.println(carInfoElementList);
        Map<String, Object> map = new HashMap<>();
        for (CarInfoElement carInfoElement : carInfoElementList) {
            map.put(carInfoElement.getKey(), carInfoElement.getValue());
        }

        //判断是否缺少必要字段
        if (map.get("plate_num").toString().isEmpty() || map.get("model").toString().isEmpty()) {
            return AjaxResult.success("缺少必要信息");
        }

        //处理发证日期,注册日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date issue_date_ = null;
        Date register_date_ = null;
        try {
            issue_date_ = dateFormat.parse(map.getOrDefault("issue_date", "").toString());
            register_date_ = dateFormat.parse(map.getOrDefault("register_date", "").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CCar cCar = new CCar();
        cCar.setPlateNum(map.get("plate_num").toString());

        //查询是否已经创建车辆信息
        List<CCar> cars = carService.selectCCarList(cCar);
        if (cars.size() > 0) {
            return AjaxResult.success("已经创建车辆信息");
        }
        //插入公司id和车队经理id
        cCar.setCompanyId(cUser.getCompanyId());
        cCar.setManagerId(userId);
        //cars为空说明没有创建车辆信息
        cCar.setModel(map.get("model").toString());
        //存入行驶证正反面
        cCar.setPermit(carInfoJson.getPermit());
        cCar.setPermitB(carInfoJson.getPermit_b());
        //存入格式化后的日期
        cCar.setRegisterDate(register_date_);
        cCar.setIssueDate(issue_date_);
        cCar.setPlateNum(map.getOrDefault("plate_num", "").toString());
        cCar.setModel(map.getOrDefault("model", "").toString());
        cCar.setOwner(map.getOrDefault("owner", "").toString());
        cCar.setVin(map.getOrDefault("vin", "").toString());
        cCar.setAddr(map.getOrDefault("addr", "").toString());
        cCar.setVehicleType(map.getOrDefault("vehicle_type", "").toString());
        cCar.setEngineNum(map.getOrDefault("engine_num", "").toString());
        cCar.setOfficialSeal(map.getOrDefault("official_seal", "").toString());
        cCar.setTotalQuality(map.getOrDefault("total_quality", "").toString());
        cCar.setUseCharacter(map.getOrDefault("use_character", "").toString());
        cCar.setLeadQuality(map.getOrDefault("lead_quality", "").toString());
        cCar.setOverallSize(map.getOrDefault("overall_size", "").toString());
        cCar.setPassengersNum(map.getOrDefault("passengers_num", "").toString());
        cCar.setPrepareQuality(map.getOrDefault("prepare_quality", "").toString());
        cCar.setRecord(map.getOrDefault("record", "").toString());
        cCar.setRemarks(map.getOrDefault("remarks", "").toString());
        cCar.setAxleCount(map.getOrDefault("axle_count", "").toString());
        cCar.setLoadQuality(map.getOrDefault("load_quality", "").toString());
        cCar.setLoadCapacity(map.getOrDefault("load_capacity", "").toString());

        //插入车辆信息
        int i = carService.insertCCar(cCar);
        if (i > 0) {
            return AjaxResult.success("创建成功");
        }
        return AjaxResult.success("创建失败");
    }

    /**
     * 修改车辆信息
     *
     * @return
     */
    @ApiOperation("修改车辆信息")
    @PostMapping("/updateCarInfo")
    public AjaxResult updateCarInfo(@ApiParam(value = "车辆信息", required = true) CCar cCar) {
        //查询车辆信息
        CCar cCar1 = carService.selectCCarByCarId(cCar.getCarId());
        Assert.notNull(cCar1, "车辆信息不存在");

        int i = carService.updateCCar(cCar);
        if (i > 0) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.success("修改失败");
    }

    /**
     * 查询车队经理手下的车
     */
    @ApiOperation("查询车队经理手下的车")
    @GetMapping("/selectManagerCar")
    public AjaxResult selectManagerCar(@ApiParam(value = "经理id", required = true) Integer mangerId) {
        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 2, "该用户不是车队经理");
        //查询车辆信息
        CCar cCar = new CCar();
        cCar.setManagerId(mangerId);
        List<CCar> cCars = carService.selectCCarList(cCar);
        List<AjaxResult> results = new ArrayList<>();

        if (!cCars.isEmpty()) {
            int count = 0;
            for (CCar car : cCars) {
                CUser user = new CUser();
                user.setCarId(car.getCarId());
                List<CUser> cUsers = cUserService.selectCUserList(user);
                if (!cUsers.isEmpty()) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("carId", car.getCarId());
                    ajaxResult.put("plateNum", car.getPlateNum());
                    ajaxResult.put("userPhone", cUsers.get(count).getUserPhone());
                    ajaxResult.put("userName", cUsers.get(count).getUserName());
                    results.add(ajaxResult);
                    count++;
                } else {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("carId", car.getCarId());
                    ajaxResult.put("plateNum", car.getPlateNum());
                    ajaxResult.put("userPhone", "无");
                    ajaxResult.put("userName", "无");
                    results.add(ajaxResult);
                    count++;
                }
            }
        }
        return AjaxResult.success(results);
    }

    /**
     * 查询车队经理手下未分配给车队长的车
     */
    @ApiOperation("查询车队经理手下未分配给车队长的车")
    @GetMapping("/selectManagerFreeCar")
    public AjaxResult selectManagerFreeCar(@ApiParam(value = "经理id", required = true) Integer mangerId) {
        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 2, "该用户不是车队经理");
        //查询车辆信息
        CCar cCar = new CCar();
//        cCar.setManagerId(mangerId);
        cCar.setCompanyId(cUser.getCompanyId());
        List<CCar> cCars = carService.selectCCarList(cCar);
        List<CCar> cCars1 = new ArrayList<>();
        for (CCar car : cCars) {
            if (car.getCarLeaderId() == 0 || car.getCarLeaderId() == null) {
                cCars1.add(car);
            }
        }
        List<AjaxResult> results = new ArrayList<>();

        if (!cCars.isEmpty()) {
            for (CCar car : cCars1) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("carId", car.getCarId());
                ajaxResult.put("plateNum", car.getPlateNum());
                ajaxResult.put("userPhone", "无");
                ajaxResult.put("userName", "无");
                results.add(ajaxResult);
            }
        }
        return AjaxResult.success(results);
    }


    /**
     * 将车辆分配给车队长（车队经理）
     */
    @ApiOperation("将车辆分配给车队长")
    @GetMapping("/distributeCar-to-carLeader")
    public AjaxResult distributeCarToCarLeader(@ApiParam(value = "车辆id", required = true) Integer carId,
                                               @ApiParam(value = "车队长id", required = true) Integer carLeaderId) {
        //查询车辆信息
        CCar cCar = carService.selectCCarByCarId(carId);
        Assert.notNull(cCar, "车辆信息不存在");
        //查询该车辆是否空闲
        Assert.isTrue(cCar.getStatus() == 0, "该车辆不是空闲状态");
        //查询车队长
        CUser cUser = cUserService.selectCUserByUserId(carLeaderId);
        Assert.notNull(cUser, "车队长不存在");
        if (cUser.getUserRole() == 1 || cUser.getUserRole() == 2) {
            cCar.setCarLeaderId(carLeaderId);
            cCar.setStatus(1);
            int i = carService.updateCCar(cCar);
            if (i > 0) {
                return AjaxResult.success("分配成功");
            }
            return AjaxResult.success("分配失败");
        }
        return AjaxResult.error("该用户不能操作车辆");
    }

    /**
     * 查询车队长手下的车
     */
    @ApiOperation("查询车队长手下的车")
    @GetMapping("/selectCarLeaderCar")
    public AjaxResult selectCarLeaderCar(@ApiParam(value = "车队长id", required = true) Integer carLeaderId) {
        // 查询车队长
        CUser cUser = cUserService.selectCUserByUserId(carLeaderId);
        Assert.notNull(cUser, "车队长不存在");
        if (cUser.getUserRole() == 1 || cUser.getUserRole() == 2) {
            // 查询车辆信息
            CCar cCar = new CCar();
            cCar.setCarLeaderId(carLeaderId);
            List<CCar> cCars = carService.selectCCarList(cCar);

            List<Object> leaderListCar = new ArrayList<>();

            for (CCar car : cCars) {
                // 查询车辆下的司机信息
                List<CUser> cUsers = cUserService.selectCUserList(new CUser() {{
                    setCarId(car.getCarId());
                }});

                List<Object> userInfoList = new ArrayList<>();
                for (CUser cUser1 : cUsers) {
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("userId", cUser1.getUserId());
                    userInfo.put("userName", cUser1.getUserName());
                    userInfo.put("userPhone", cUser1.getUserPhone());
                    userInfo.put("userHeader", cUser1.getUserHeader());
                    userInfoList.add(userInfo);
                }

                // 如果没有司机信息，添加一条空记录
                Map<String, Object> carInfo = new HashMap<>();
                carInfo.put("carId", car.getCarId());
                carInfo.put("plateNum", car.getPlateNum());
                carInfo.put("userInfo", userInfoList);

                leaderListCar.add(carInfo);
            }

            return AjaxResult.success(Collections.singletonMap("leaderListCar", leaderListCar));
        }
        return AjaxResult.error("该用户不是车队长");
    }


    /**
     * 查询车队长手下未绑定司机的车辆
     */
    @ApiOperation("查询车队长手下未绑定司机的车辆")
    @GetMapping("/selectUnbindDriverCar")
    public AjaxResult selectUnbindDriverCar(@ApiParam(value = "车队长id", required = true) Integer carLeaderId) {
        //查询车队经理
        CUser cUser = cUserService.selectCUserByUserId(carLeaderId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 1, "该用户不是车队长");
        //查询车辆信息
        CCar cCar = new CCar();
        cCar.setManagerId(carLeaderId);
        cCar.setCarLeaderId(0);
        List<CCar> cCars = carService.selectCCarList(cCar);
        List<AjaxResult> results = new ArrayList<>();
        int count = 0;
        if (!cCars.isEmpty()) {
            for (CCar car : cCars) {
                CUser user = new CUser();
                user.setCarId(car.getCarId());
                List<CUser> cUsers = cUserService.selectCUserList(user);
                if (!cUsers.isEmpty()) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("carId", car.getCarId());
                    ajaxResult.put("plateNum", car.getPlateNum());
                    ajaxResult.put("userPhone", cUsers.get(count).getUserPhone());
                    ajaxResult.put("userName", cUsers.get(count).getUserName());
                    results.add(ajaxResult);
                    count++;
                } else {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("carId", car.getCarId());
                    ajaxResult.put("plateNum", car.getPlateNum());
                    ajaxResult.put("userPhone", "无");
                    ajaxResult.put("userName", "无");
                    results.add(ajaxResult);
                    count++;
                }
            }
        }
        return AjaxResult.success(results);
    }


    /**
     * 将车辆分配给司机（车队长）
     */
    @ApiOperation("将车辆分配给司机")
    @GetMapping("/distributeCar-to-driver")
    public AjaxResult distributeCarToDriver(@ApiParam(value = "车辆id", required = true) Integer carId,
                                            @ApiParam(value = "司机id", required = true) Integer driverId) {
        //查询车辆信息
        CCar cCar = carService.selectCCarByCarId(carId);
        Assert.notNull(cCar, "车辆信息不存在");
        //查询该车辆是否已经分配两名司机
        CUser user = new CUser();
        user.setCarId(carId);
        List<CUser> cUsers = cUserService.selectCUserList(user);
        Assert.isTrue(cUsers.size() < 2, "该车辆已经分配两名司机");
        //查询司机
        CUser cUser = cUserService.selectCUserByUserId(driverId);
        if (cUser != null) {
            //判断是不是我们公司的
            if (!Objects.equals(cUser.getCompanyId(), cCar.getCompanyId())) {
                //判断是否是别的公司的
                if (cUser.getCompanyId() != 0) {
                    return AjaxResult.error("该用户不是本公司的");
                } else {
                    //自动绑定为该车队长手下的人并分配车辆
                    CompanyBind companyBind = new CompanyBind();
                    companyBind.setCompanyId(cCar.getCompanyId());
                    companyBind.setMangerId(cCar.getManagerId());
                    companyBind.setSysUserId(Long.valueOf(cCar.getCarLeaderId()));
                    companyBind.setConsumerId(driverId);
                    int i = companyBindService.insertCompanyBind(companyBind);
                    Assert.isTrue(i > 0, "绑定失败");
                    //分配给用户
                    cUser.setCompanyId(cCar.getCompanyId());
                    cUser.setCarId(carId);
                    int i1 = cUserService.updateCUser(cUser);
                    return AjaxResult.success("分配成功");
                }
            } else {
                //分配给用户
                cUser.setCompanyId(cCar.getCompanyId());
                cUser.setCarId(carId);
                int i1 = cUserService.updateCUser(cUser);
            }
        }
        //设置公司名称信息
        CCompany cCompany = companyService.selectCCompanyByCompanyId(cCar.getCompanyId());
        if (cCompany != null) {
            companyCache.cacheCompanyInfo(driverId, cCompany.getCompanyName());
        }


        return AjaxResult.success("分配成功");

    }

    /**
     * 车队长解绑车辆
     */
    @ApiOperation("车队长让司机从车上下来")
    @GetMapping("/unbindCarForCarLeader")
    public AjaxResult unbindCarForCarLeader(@ApiParam(value = "司机id", required = true) Integer userId) {
//查询用户信息
        CUser cUser = cUserService.selectCUserByUserId(userId);
        Assert.notNull(cUser, "用户不存在");
        //查询车辆信息
        CCar cCar = carService.selectCCarByCarId(cUser.getCarId());
        Assert.notNull(cCar, "车辆信息不存在");
        //更新车辆绑定状态
        cUser.setCarId(0);
        //删除公司名称信息
        companyCache.removeCompanyInfo(userId);
        int i = cUserService.updateCUser(cUser);
        if (i > 0) {
            return AjaxResult.success("解绑成功");
        }
        return AjaxResult.success("解绑失败");
    }

    /**
     * 车队经理解绑车辆
     */
    @ApiOperation("车队经理解绑车辆")
    @GetMapping("/unbindCarForManager")
    public AjaxResult unbindCarForManager(@ApiParam(value = "车辆id", required = true) Integer carId) {
        //查询车辆信息
        CCar cCar = carService.selectCCarByCarId(carId);
        Assert.notNull(cCar, "车辆信息不存在");
        //更新车辆绑定状态
        cCar.setCarLeaderId(0);
        cCar.setStatus(0);
        int i = carService.updateCCar(cCar);
        if (i > 0) {
            return AjaxResult.success("解绑成功");
        }
        return AjaxResult.success("解绑失败");
    }


    /**
     * 车队经理解绑车队长
     */
    @ApiOperation("车队经理解绑车队长")
    @GetMapping("/unbindCarLeaderForManager")
    public AjaxResult unbindCarLeaderForManager(@ApiParam(value = "被解绑车队长id", required = true) Integer carLeaderId,
                                                @ApiParam(value = "车队经理id", required = true) Integer mangerId) {
        if (carLeaderId == null || carLeaderId == 0) {
            return AjaxResult.error("车队长id不能为空");
        }
        if (mangerId == null || mangerId == 0) {
            return AjaxResult.error("车队经理id不能为空");
        }

        //查询用户信息
        CUser cUser = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(cUser, "车队经理不存在");
        Assert.isTrue(cUser.getUserRole() == 2, "该用户不是车队经理");

        //查询该车队长手下是否还有员工或车辆
        CCar cCar = new CCar();
        cCar.setCarLeaderId(carLeaderId);
        List<CCar> cCars = carService.selectCCarList(cCar);
        Assert.isTrue(cCars.isEmpty(), "该车队长手下还有车辆，不能解绑");
        CompanyBind companyBind1 = new CompanyBind();
        companyBind1.setMangerId(mangerId);
        companyBind1.setSysUserId(Long.valueOf(carLeaderId));
        List<CompanyBind> companyBinds1 = companyBindService.selectCompanyBindList(companyBind1);
        if (companyBinds1.isEmpty()) {
            return AjaxResult.error("没有该车队长关系");
        }
        if (companyBinds1.get(0).getConsumerId().equals(0) || companyBinds1.get(0).getConsumerId() == 0 || companyBinds1.get(0).getConsumerId() == null) {
            //解绑员工
            //查询绑定
            CompanyBind companyBind = new CompanyBind();
            companyBind.setSysUserId(Long.valueOf(carLeaderId));
            companyBind.setMangerId(mangerId);
            List<CompanyBind> companyBinds = companyBindService.selectCompanyBindList(companyBind);
            if (companyBinds.isEmpty()) {
                return AjaxResult.error("用户未绑定公司");
            }
            CompanyBind bind = companyBinds.get(0);
            int i = companyBindService.deleteCompanyBindByBindId(bind.getBindId());
            Assert.isTrue(i > 0, "解绑失败");

            //更新用户信息
            CUser user = cUserService.selectCUserByUserId(carLeaderId);
//            车队长和车队经理是同一个人
            if (carLeaderId.equals(mangerId)) {
                return AjaxResult.success("解绑成功");
            } else {
                user.setUserRole(0);
                cUserService.updateCUser(user);
                return AjaxResult.success("解绑成功");
            }
        } else {
            return AjaxResult.error("该车队长还有员工，不能解绑");
        }

    }

    @ApiOperation("查询车队经理所在公司所有员工")
    @GetMapping("/selectManagerLeaderStaff")
    public AjaxResult selectManagerLeaderStaff(@ApiParam(value = "经理id", required = true) Integer mangerId) {
        // 查询车队经理
        CUser manager = cUserService.selectCUserByUserId(mangerId);
        Assert.notNull(manager, "车队经理不存在");
        Assert.isTrue(manager.getUserRole() == 2, "该用户不是车队经理");

        //查询公司所有员工
        CUser userQuery = new CUser();
        userQuery.setCompanyId(manager.getCompanyId());
        List<CUser> companyEmployees = cUserService.selectCUserList(userQuery);

        List<AjaxResult> employees = new ArrayList<>();


        for (CUser employee : companyEmployees) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("value", employee.getUserId());
            ajaxResult.put("label", (employee.getUserName() == null || employee.getUserName().isEmpty())
                    ? (employee.getUserNick() + " - " + employee.getUserPhone())
                    : (employee.getUserName() + " - " + employee.getUserPhone()));
            employees.add(ajaxResult);
        }

        return AjaxResult.success(employees);
    }

    //查询本公司的车队经理
    @ApiOperation("查询本公司的车队经理")
    @GetMapping("/queryManagerByCompanyId")
    public List<AjaxResult> queryManagerByCompanyId(@ApiParam(value = "公司id", required = true) Integer companyId) {
        CUser cUser = new CUser();
        cUser.setCompanyId(companyId);
        cUser.setUserRole(2);
        List<CUser> cUsers = cUserService.selectCUserList(cUser);
        if (cUsers.isEmpty()) {
            return new ArrayList<>();
        }
        List<AjaxResult> results = new ArrayList<>();
        for (CUser user : cUsers) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("mangerId", user.getUserId());
            ajaxResult.put("userName", ObjectUtil.isNotEmpty(user.getUserName()) ? user.getUserName() : user.getUserNick());
            results.add(ajaxResult);
        }
        return results;
    }

    //查询本公司的车队长
    @ApiOperation("查询本公司的车队长")
    @GetMapping("/queryCarLeaderByCompanyId")
public List<AjaxResult> queryCarLeaderByCompanyId(@ApiParam(value = "公司id", required = true) Integer companyId) {
        CUser cUser = new CUser();
        cUser.setCompanyId(companyId);
        cUser.setUserRole(1);
        List<CUser> cUsers = cUserService.selectCUserList(cUser);
        if (cUsers.isEmpty()) {
            return new ArrayList<>();
        }
        List<AjaxResult> results = new ArrayList<>();
        for (CUser user : cUsers) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("leaderId", user.getUserId());
            ajaxResult.put("userName", user.getUserNick());
            results.add(ajaxResult);
        }
        return results;
    }
}
